package com.duolaibei.pay.smscan;

import android.content.Intent;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.duolaibei.pay.R;
import com.duolaibei.pay.activity.DealDetailsActivity;
import com.duolaibei.pay.base.BaseActivity;
import com.duolaibei.pay.base.Constants;
import com.duolaibei.pay.bean.PayOrder;
import com.duolaibei.pay.greendao.PayOrderDao;
import com.duolaibei.pay.http.BaseCallback;
import com.duolaibei.pay.http.HttpRetrofit;
import com.duolaibei.pay.http.ParamsUtils;
import com.duolaibei.pay.http.Result;
import com.duolaibei.pay.http.api.ApiName;
import com.duolaibei.pay.http.api.SerivceApi;
import com.duolaibei.pay.utils.GreenDaoManager;
import com.duolaibei.pay.utils.ProgressDialogUtils;
import com.duolaibei.pay.utils.SharedPreferencesUtils;
import com.duolaibei.pay.utils.ToastUtils;
import com.sunmi.scan.Config;
import com.sunmi.scan.Image;
import com.sunmi.scan.ImageScanner;
import com.sunmi.scan.Symbol;
import com.sunmi.scan.SymbolSet;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.List;

import retrofit2.Call;
import retrofit2.Response;


public class SunmiScanActivity extends BaseActivity
        implements SurfaceHolder.Callback, BaseCallback<Result<PayOrder>> {
    private Camera mCamera;
    private SurfaceHolder mHolder;
    private SurfaceView surface_view;
    private ImageScanner scanner;//声明扫描器
    private Handler autoFocusHandler;
    private AsyncDecode asyncDecode;
    SoundUtils soundUtils;
    private boolean vibrate;
    public int decode_count = 0;

    private FinderView finder_view;

    private int type = 0;
    private PayOrderDao payOrderDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getContentViewResId() {
        return R.layout.ac_sunmi_scan_finder;
    }

    @Override
    public void intiViews() {
        surface_view = (SurfaceView) findViewById(R.id.surface_view);
        finder_view = (FinderView) findViewById(R.id.finder_view);
        mHolder = surface_view.getHolder();
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mHolder.addCallback(this);

        scanner = new ImageScanner();//创建扫描器
        scanner.setConfig(0, Config.X_DENSITY, 2);//行扫描间隔
        scanner.setConfig(0, Config.Y_DENSITY, 2);//列扫描间隔
        scanner.setConfig(0, Config.ENABLE_MULTILESYMS, 0);//是否开启同一幅图一次解多个条码,0表示只解一个，1为多个
        scanner.setConfig(0, Config.ENABLE_INVERSE, 0);//是否解反色的条码
        scanner.setConfig(Symbol.PDF417, Config.ENABLE, 0);//是否禁止PDF417码，默认开启

        autoFocusHandler = new Handler();
        asyncDecode = new AsyncDecode();
        decode_count = 0;
    }

    @Override
    public String setTitle() {
        Intent intent = getIntent();
        String title = "";
        if (null != intent) {
            title = intent.getStringExtra("title");
            type = intent.getIntExtra("type", 0);
        }
        return title;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (mHolder.getSurface() == null) {
            return;
        }
        try {
            mCamera.stopPreview();
        } catch (Exception e) {
        }
        try {
            //摄像头预览分辨率设置和图像放大参数设置，非必须，根据实际解码效果可取舍
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setPreviewSize(800, 480);  //设置预览分辨率
            //     parameters.set("zoom", String.valueOf(27 / 10.0));//放大图像2.7倍
            mCamera.setParameters(parameters);
            mCamera.setDisplayOrientation(90);//竖屏显示
            mCamera.setPreviewDisplay(mHolder);
            mCamera.setPreviewCallback(previewCallback);
            mCamera.startPreview();
            mCamera.autoFocus(autoFocusCallback);
        } catch (Exception e) {
            Log.d("DBG", "Error starting camera preview: " + e.getMessage());
        }
    }

    /**
     * 预览数据
     */
    PreviewCallback previewCallback = new PreviewCallback() {
        public void onPreviewFrame(byte[] data, Camera camera) {
            if (asyncDecode.isStoped() && scan_count < 2) {
                Camera.Parameters parameters = camera.getParameters();
                Size size = parameters.getPreviewSize();//获取预览分辨率

                //创建解码图像，并转换为原始灰度数据，注意图片是被旋转了90度的
                Image source = new Image(size.width, size.height, "Y800");
                Rect scanImageRect = finder_view.getScanImageRect(size.height, size.width);
                //图片旋转了90度，将扫描框的TOP作为left裁剪
                source.setCrop(scanImageRect.top, scanImageRect.left, scanImageRect.height(), scanImageRect.width());
                source.setData(data);//填充数据
                asyncDecode = new AsyncDecode();
                asyncDecode.execute(source);//调用异步执行解码
            }
        }
    };

    private int scan_count = 0;

    private class AsyncDecode extends AsyncTask<Image, Void, Void> {
        private boolean stoped = true;
        private String str = "";
        private int nsyms = 0;//解码，返回值为0代表失败，>0表示成功

        @Override
        protected Void doInBackground(Image... params) {
            stoped = false;
            StringBuilder sb = new StringBuilder();
            Image src_data = params[0];//获取灰度数据
            nsyms = scanner.scanImage(src_data);
            if (nsyms != 0) {
//                playBeepSoundAndVibrate();//解码成功播放提示音
                SymbolSet syms = scanner.getResults();//获取解码结果
                for (Symbol sym : syms) {
                    sb.append(sym.getResult());
                }
            }
            str = sb.toString();
            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
            super.onPostExecute(v);
            stoped = true;
            if (null == str || str.equals("")) {
            } else {
                scan_count++;
                String result = str.trim();
                if (type == 100) {//查单
                    ProgressDialogUtils.showProgress(SunmiScanActivity.this, getString(R.string.select_deal_now));
                    ProgressDialogUtils.getmDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                    if (result.length() == 17) {

                        //内部订单号
                        HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class).request(
                                SharedPreferencesUtils.getAppid()
                                , ApiName.SELECT_DEAL,
                                "",
                                result,
                                ParamsUtils.getOrderParams(result))
                                .enqueue(SunmiScanActivity.this);

                    } else if (result.length() > 17) {
                        //第三方订单号
                        HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class).request(SharedPreferencesUtils.getAppid()
                                , ApiName.SELECT_DEAL, result, "", ParamsUtils.getOrderParams(result)).enqueue(SunmiScanActivity.this);
                    }
                } else if (type == 200) {//收款
                    Intent resultIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putInt(Constants.SCAN_STATE, nsyms);
                    bundle.putString(Constants.SCAN_CONTENT, result);
                    resultIntent.putExtras(bundle);
                    setResult(RESULT_OK, resultIntent);
                    finish();
                } else if (type == 300) {//退款
                    ProgressDialogUtils.showProgress(SunmiScanActivity.this, getString(R.string.refund_now));
                    if (result.length() == 17) {
                        HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class).refund(SharedPreferencesUtils.getAppid(), ApiName.RE_FUND, ParamsUtils.refund(result),
                                "", result, SharedPreferencesUtils.getWorkMenId()).enqueue(callback);
                    } else if (result.length() > 17) {
                        HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class).refund(SharedPreferencesUtils.getAppid(), ApiName.RE_FUND, ParamsUtils.refund(result), result
                                , "", SharedPreferencesUtils.getWorkMenId()).enqueue(callback);
                    }
                } else {
                    //失败退出
                    Intent resultIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putInt(Constants.SCAN_STATE, nsyms);
                    bundle.putString(Constants.SCAN_CONTENT, "");
                    resultIntent.putExtras(bundle);
                    setResult(RESULT_OK, resultIntent);
                    finish();
                }
            }
        }

        private boolean isStoped() {
            return stoped;
        }
    }

    @Override
    public void onResponse(Call<Result<PayOrder>> call, Response<Result<PayOrder>> response) {
        ProgressDialogUtils.dismissProgress();
        if (response.code() == 200) {
            if (response.body().getStatus().equals("1")) {
                PayOrder order = response.body().getResult();
                Intent intent = new Intent(this, DealDetailsActivity.class);
                intent.putExtra("order", order);
                startActivity(intent);
            } else {
                ToastUtils.showToast(this, response.body().getInfo(), 3000);
            }
        }
        finish();
    }

    @Override
    public void onFailure(Call<Result<PayOrder>> call, Throwable t) {
        ProgressDialogUtils.dismissProgress();
        Log.v("onFailure", "onFailure ! message:" + t.getMessage());
    }

    /**
     * 退款回调
     */
    BaseCallback<Result<PayOrder>> callback = new BaseCallback<Result<PayOrder>>() {
        @Override
        public void onResponse(Call<Result<PayOrder>> call, Response<Result<PayOrder>> response) {
            ProgressDialogUtils.dismissProgress();
            if (response.code() == 200) {
                if (response.body().getStatus().equals("1")) {
                    PayOrder order = response.body().getData();
                    ToastUtils.showToast(SunmiScanActivity.this, R.string.refund_succ);
                    payOrderDao = GreenDaoManager.getInstance().getNewSession().getPayOrderDao();
                    List<PayOrder> list = payOrderDao.queryBuilder().where(PayOrderDao.Properties.Out_trade_no.eq(order.getOut_trade_no())).build().list();
                    order.setId(list.get(0).getId());
                    payOrderDao.update(order);
                    Intent intent = new Intent(SunmiScanActivity.this, DealDetailsActivity.class);
                    intent.putExtra("type", 300);
                    intent.putExtra("order", order);
                    startActivity(intent);
                } else {
                    ToastUtils.showToast(SunmiScanActivity.this, response.body().getInfo());
                }
            }
            finish();
        }

        @Override
        public void onFailure(Call<Result<PayOrder>> call, Throwable t) {
            ProgressDialogUtils.dismissProgress();
            Log.v("onFailure", "error message:" + t.getMessage());
        }
    };

    /**
     * 自动对焦回调
     */
    AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            autoFocusHandler.postDelayed(doAutoFocus, 1000);
        }
    };

    //自动对焦
    private Runnable doAutoFocus = new Runnable() {
        public void run() {
            if (null == mCamera || null == autoFocusCallback) {
                return;
            }
            mCamera.autoFocus(autoFocusCallback);
        }
    };

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mCamera = Camera.open();
        } catch (Exception e) {
            mCamera = null;
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    private void initBeepSound() {
        if (soundUtils == null) {
            soundUtils = new SoundUtils(this, SoundUtils.RING_SOUND);
            soundUtils.putSound(0, R.raw.beep);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initBeepSound();
        vibrate = false;
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (soundUtils != null) {
            soundUtils.playSound(0, SoundUtils.SINGLE_PLAY);
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

}
